﻿using Interface.Cache;
using Interface.Core.Controllers;
using Interface.Core.Utility;
using Interface.Mvc.Areas.Utility.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Interface.Mvc.Areas.Utility.Controllers
{
    public class SmsController : CoreController
    {
        private IList<IPFilter> Filter
        {
            get
            {
                return CommonCache.GetCache("Utility_Sms_Filter", () =>
                {
                    return new List<IPFilter>();
                });
            }
            set { CommonCache.SetCache("Utility_Sms_Filter", value); }
        }

        private bool IsExist(string mobile, string ip)
        {
            var filter = Filter;
            bool bit = filter.Count(m => m.Mobile == mobile && m.IP == ip && m.Time > DateTime.Now.AddMinutes(-2)) > 0;
            if (!bit)
            {
                bit = filter.Count(m => m.IP == ip && m.Time > DateTime.Now.AddMinutes(-2)) > 10;
            }
            return bit;
        }

        private void AddFilter(string mobile, string ip)
        {
            var filter = Filter;
            filter.Add(new IPFilter
            {
                Mobile = mobile,
                IP = ip,
                Time = DateTime.Now
            });
            Filter = filter;
        }

        /// <summary>
        /// 基础发送短信功能
        /// params: mobile, content
        /// </summary>
        [HttpPost]
        public string Send(string mobile, string content, string ip)
        {
            if (IsExist(mobile, ip))
            {
                return ResultUtility.FailureResult("发送频率超过设定!");
            }
            else { AddFilter(mobile, ip); }

            int count = Filter.Count(m => m.Mobile == mobile && m.IP == ip);

            ResultEntity re = db.Crm.StoredQuery<ResultEntity>("Scrm_Sp_SmsSend", new
            {
                mobile = mobile,
                content = content,
                count = count
            }).FirstOrDefault();

            return ResultUtility.UnknownResult(re.success, re.imessage, re.imessage);
        }
    }
}